package com.gardenguell.salad.data.client;

import android.text.TextUtils;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.util.SharedPreferenceUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by absurd on 2015/12/5.
 */
public class ParamsBuilder {

    private static final String UTF_8 = "UTF_8";

    private Map<String,String> params;

    private String target;

    public static ParamsBuilder create(String targetUrl){
        ParamsBuilder pb = new ParamsBuilder();
        pb.params = new HashMap<String, String>();
        pb.target = targetUrl;
        return pb;
    }


    public ParamsBuilder bindAuthToken(){
        String token = SharedPreferenceUtil.getInstance().get(AppConstant.PREF_TOKEN.AUTH_TOKEN, "");
        this.params.put("token", token);
        return this;
    }

    public ParamsBuilder add(String key, String value){
        this.params.put(key, value);
        return this;
    }

    public String toUrl(){
        StringBuilder sb = new StringBuilder(target);
        sb.append('?');
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                if (!TextUtils.isEmpty(entry.getValue())) {
                    sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), UTF_8)).append('&');
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.deleteCharAt(sb.length()-1);
        return new String(sb);
    }
}
